package com.ejd.web.vo.common;

import java.text.DecimalFormat;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.faces.render.RenderKit;

import net.sf.cglib.beans.BeanCopier;


import com.ejd.controller.LoginController;
import com.ejd.service.IConsigneeService;
import com.ejd.service.ICouponService;
import com.ejd.service.ICustomerService;
import com.ejd.service.INCounterService;
import com.ejd.service.IOrderService;
import com.ejd.utils.CurrencyDecimalPlaceUtil;
import com.ejd.utils.DESPlusUtil;
import com.ejd.utils.DateTimeUtil;
import com.ejd.utils.DeliveryUtil;
import com.ejd.utils.FormatUtil;
import com.ejd.utils.InventoryUtil;
import com.ejd.utils.MessageFactory;
import com.ejd.utils.NCounterUtil;
import com.ejd.utils.PageExistUtil;
import com.ejd.utils.PaymentTypeUtil;
import com.ejd.utils.PaymentUtil;
import com.ejd.utils.RegionUtil;
import com.ejd.utils.SpringFacesUtil;
import com.ejd.utils.ValidatorUtil;
import com.ejd.web.bo.AbstractOrder;
import com.ejd.web.bo.Product;
import com.ejd.web.bo.impl.Color;
import com.ejd.web.bo.impl.Consignee;
import com.ejd.web.bo.impl.Consultation;
import com.ejd.web.bo.impl.Coupon;
import com.ejd.web.bo.impl.Customer;
import com.ejd.web.bo.impl.Delivery;
import com.ejd.web.bo.impl.NCounter;
import com.ejd.web.bo.impl.Order;
import com.ejd.web.bo.impl.OrderDetail;
import com.ejd.web.bo.impl.Payment;
import com.ejd.web.bo.impl.PaymentType;
import com.ejd.web.constant.EjdConstants;
import com.ejd.web.constant.ManageBeanConstants;
import com.ejd.web.constant.SpringBeanConstants;
import com.ejd.web.vo.common.ColorVo;
import com.ejd.web.vo.common.ConsultationVo;
import com.ejd.web.vo.common.CustomerVo;
import com.ejd.web.vo.common.OrderDetailVo;
import com.ejd.web.vo.common.OrderVo;
import com.ejd.web.vo.customer.LoginCustomerPageBean;
import com.ejd.web.vo.genl.ExistInvoiceTypeBean;
import com.ejd.web.vo.shopcart.Inventory;
import com.ejd.web.vo.shopcart.InventoryItem;
import com.ejd.web.vo.shopcart.ShopCartBean;

public class OrderCrudBean {
	private Inventory cart;
	private OrderVo order = new OrderVo();
	private OrderVo orderEdit = new OrderVo();
	private boolean useDefaultAddress = false;
	private SelectItem[] addressItems;
	private String actionSetAddress;
	private boolean successSetAddress = false;
	public List<String> updateAddressErrorMessages = new ArrayList<String>();
	private SelectItem[] provinceItems = null;
	private SelectItem[] cityItems = null;
	private SelectItem[] countyItems = null;
	private List<Delivery> deliveries = new ArrayList<Delivery>();
	private List<Payment> payments = new ArrayList<Payment>();
	private List<PaymentType> paymentTypes = new ArrayList<PaymentType>();
	
	//invoice about start
	private String actionSetInvoice;
	private boolean successSetInvoice;
	public List<String> updateInvoiceErrorMessages = new ArrayList<String>();
	//invoice about end
	//order error message start
	public List<String> orderErrorMessage = new ArrayList<String>();
	//order error message end
	private String couponAccount;
	private Double couponScore = new Double(0D);
	private boolean couponChecked = false;
	private String couponErrorMessage;
	private Double integrationScore = new Double(0D);
	private boolean integrationChecked = false;
	private String integrationErrorMessage;
	private boolean haveSelected;
	private Integer maxBuyGoodsNumber = 0;
	public Inventory getCart() {
		return cart;
	}

	public void setCart(Inventory cart) {
		this.cart = cart;
	}

	protected void init() {
		cart = new Inventory();
	}

	public OrderVo getOrder() {
		return order;
	}

	public void setOrder(OrderVo order) {
		this.order = order;
	}

	public OrderVo getOrderEdit() {
		return orderEdit;
	}

	public void setOrderEdit(OrderVo orderEdit) {
		this.orderEdit = orderEdit;
	}

	public boolean isUseDefaultAddress() {
		return useDefaultAddress;
	}

	public void setUseDefaultAddress(boolean useDefaultAddress) {
		this.useDefaultAddress = useDefaultAddress;
	}

	public SelectItem[] getAddressItems() {
		return addressItems;
	}

	public void setAddressItems(SelectItem[] addressItems) {
		this.addressItems = addressItems;
	}

	public String getActionSetAddress() {
		return actionSetAddress;
	}

	public void setActionSetAddress(String actionSetAddress) {
		this.actionSetAddress = actionSetAddress;
	}

	public boolean isSuccessSetAddress() {
		return successSetAddress;
	}

	public void setSuccessSetAddress(boolean successSetAddress) {
		this.successSetAddress = successSetAddress;
	}

	public List<String> getUpdateAddressErrorMessages() {
		return updateAddressErrorMessages;
	}

	public void setUpdateAddressErrorMessages(
			List<String> updateAddressErrorMessages) {
		this.updateAddressErrorMessages = updateAddressErrorMessages;
	}

	public SelectItem[] getProvinceItems() {
		return provinceItems;
	}

	public void setProvinceItems(SelectItem[] provinceItems) {
		this.provinceItems = provinceItems;
	}

	public SelectItem[] getCityItems() {
		return cityItems;
	}

	public void setCityItems(SelectItem[] cityItems) {
		this.cityItems = cityItems;
	}

	public SelectItem[] getCountyItems() {
		return countyItems;
	}

	public void setCountyItems(SelectItem[] countyItems) {
		this.countyItems = countyItems;
	}

	public List<Delivery> getDeliveries() {
		return deliveries;
	}

	public void setDeliveries(List<Delivery> deliveries) {
		this.deliveries = deliveries;
	}

	public List<Payment> getPayments() {
		return payments;
	}

	public void setPayments(List<Payment> payments) {
		this.payments = payments;
	}

	public List<PaymentType> getPaymentTypes() {
		return paymentTypes;
	}

	public void setPaymentTypes(List<PaymentType> paymentTypes) {
		this.paymentTypes = paymentTypes;
	}

	public String getActionSetInvoice() {
		return actionSetInvoice;
	}

	public void setActionSetInvoice(String actionSetInvoice) {
		this.actionSetInvoice = actionSetInvoice;
	}

	public boolean isSuccessSetInvoice() {
		return successSetInvoice;
	}

	public void setSuccessSetInvoice(boolean successSetInvoice) {
		this.successSetInvoice = successSetInvoice;
	}

	public List<String> getUpdateInvoiceErrorMessages() {
		return updateInvoiceErrorMessages;
	}

	public void setUpdateInvoiceErrorMessages(List<String> updateInvoiceErrorMessages) {
		this.updateInvoiceErrorMessages = updateInvoiceErrorMessages;
	}

	public List<String> getOrderErrorMessage() {
		return orderErrorMessage;
	}

	public void setOrderErrorMessage(List<String> orderErrorMessage) {
		this.orderErrorMessage = orderErrorMessage;
	}

	public String getCouponAccount() {
		return couponAccount;
	}

	public void setCouponAccount(String couponAccount) {
		this.couponAccount = couponAccount;
	}

	public Double getCouponScore() {
		return couponScore;
	}

	public void setCouponScore(Double couponScore) {
		this.couponScore = couponScore;
	}

	public boolean isCouponChecked() {
		return couponChecked;
	}

	public void setCouponChecked(boolean couponChecked) {
		this.couponChecked = couponChecked;
	}

	public String getCouponErrorMessage() {
		return couponErrorMessage;
	}

	public void setCouponErrorMessage(String couponErrorMessage) {
		this.couponErrorMessage = couponErrorMessage;
	}

	public Double getIntegrationScore() {
		return integrationScore;
	}

	public void setIntegrationScore(Double integrationScore) {
		this.integrationScore = integrationScore;
	}

	public boolean isIntegrationChecked() {
		return integrationChecked;
	}

	public void setIntegrationChecked(boolean integrationChecked) {
		this.integrationChecked = integrationChecked;
	}

	public String getIntegrationErrorMessage() {
		return integrationErrorMessage;
	}

	public void setIntegrationErrorMessage(String integrationErrorMessage) {
		this.integrationErrorMessage = integrationErrorMessage;
	}
	
	public Integer getMaxBuyGoodsNumber() {
		return maxBuyGoodsNumber;
	}

	public void setMaxBuyGoodsNumber(Integer maxBuyGoodsNumber) {
		this.maxBuyGoodsNumber = maxBuyGoodsNumber;
	}

	public boolean isHaveSelected() {
		return this.getCart().isHaveSelected();
	}


	public Double getNeedPayment(){
		double couponScore = (null == this.getCouponScore())?0.0:(new Double(this.getCouponScore())).doubleValue();
		double integrationScore = (null == this.getIntegrationScore())?0.0:(new Double(this.getIntegrationScore())).doubleValue() / 10;
		double result = this.getCart().getInventoryPriceTotal() - couponScore - integrationScore;
		return new Double(result);
	}
	public OrderCrudBean(){
		
	}
	
	public String addInventoryItem() {
		ShopCartBean shopCart = (ShopCartBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.SHOP_CART_BEAN_NAME);
		if (shopCart.getCart().getInventoryQuantityTotal() > EjdConstants.MAX_BUY_GOODS_NUMBER - 1) {
			return null;
		}
		String code = (String) SpringFacesUtil.getRequestParameter("productCode");
		String primaryCategoryCode = (String) SpringFacesUtil.getRequestParameter("primaryCategoryCode");
		String specialField1 = (String) SpringFacesUtil.getRequestParameter("specialField1");
		String specialField2 = (String) SpringFacesUtil.getRequestParameter("specialField2");
		Integer number = Integer.valueOf(SpringFacesUtil.getRequestParameter("number").toString());
		Integer maxBuyNumber = Integer.valueOf(SpringFacesUtil.getRequestParameter("maxBuyNumber").toString());
		if (null == code || "".equals(code)) {
			return null;
		}
		InventoryItem newInventoryItem = new InventoryItem();
		newInventoryItem = InventoryUtil.getInventoryItemByParam(code, primaryCategoryCode, specialField1, specialField2);
		if (newInventoryItem.isPromotional()) {
			newInventoryItem.setSalesPrice(CurrencyDecimalPlaceUtil.round(newInventoryItem.getRetailPrice() * newInventoryItem.getPercentageOfPro(),2,EjdConstants.ROUNDING_METHOD_UP));
		} else {
			newInventoryItem.setSalesPrice(newInventoryItem.getRetailPrice());
		}
		newInventoryItem.setSalesQuantity(number);
		newInventoryItem.setMaxBuyNumber(maxBuyNumber);
		shopCart.getCart().addInventoryItem(newInventoryItem);
		shopCart.getCart().recalculateIventory();
		
		
		return null;
	}
	public String clearShoppingCart() {
		if (null != this.getCart() && null != this.getCart().getInventory() && (!(this.getCart().getInventory().isEmpty()))) {
			this.getCart().getInventory().clear();
			this.getCart().setInventoryPriceTotal(0.0);
			this.getCart().setInventoryQuantityTotal(0);
			this.getCart().setHaveSelected(false);
		}
		return null;
	}
	public String removeOneSelectedFromShoppingCart(){
		String selectedProductCode = (String) SpringFacesUtil.getRequestParameter("selectedProductCode");
		String primaryCategoryCode = (String) SpringFacesUtil.getRequestParameter("primaryCategoryCode");
		String specialField1 = (String) SpringFacesUtil.getRequestParameter("specialField1");
		String specialField2 = (String) SpringFacesUtil.getRequestParameter("specialField2");
		if (null == this.getCart() || null == this.getCart().getInventory()) {
			return null;
		}
		if (this.getCart().getInventory().isEmpty()) {
			return null;
		}
		ArrayList<InventoryItem> curCartInventory = this.getCart().getInventory();
		for (int i = curCartInventory.size()-1 ; i >= 0; i--) {
			InventoryItem tempInventoryItem = curCartInventory.get(i);
			if ((null == specialField1 || "".equals(specialField1)) && (null == specialField2 || "".equals(specialField2))) {
				if ((selectedProductCode.equals(tempInventoryItem.getCode().toString())) && (primaryCategoryCode.equals(tempInventoryItem.getPrimaryCategoryCode()))) {
					curCartInventory.remove(i);
					break;
				}
			} else if ((null != specialField1 || !("".equals(specialField1))) && (null != specialField2 || !("".equals(specialField2)))) {
				if ((selectedProductCode.equals(tempInventoryItem.getCode().toString())) && (primaryCategoryCode.equals(tempInventoryItem.getPrimaryCategoryCode())) && (specialField1.equals(tempInventoryItem.getSpecialField1())) && (specialField2.equals(tempInventoryItem.getSpecialField2()))) {
					curCartInventory.remove(i);
					break;
				}
			} else if ((null != specialField1 || !("".equals(specialField1))) && (null == specialField2 || ("".equals(specialField2)))) {
				if ((selectedProductCode.equals(tempInventoryItem.getCode().toString())) && (primaryCategoryCode.equals(tempInventoryItem.getPrimaryCategoryCode())) && (specialField1.equals(tempInventoryItem.getSpecialField1()))) {
					curCartInventory.remove(i);
					break;
				}
			}
		}
		this.getCart().recalculateIventory();
		return EjdConstants.SHOP_CART + "?faces-redirect=true";
	}
	public String removeMulSelectedFromShoppingCart() {
		if (null == this.getCart() || null == this.getCart().getInventory()) {
			return null;
		}
		if (this.getCart().getInventory().isEmpty()) {
			return null;
		}
		ArrayList<InventoryItem> curCartInventory = this.getCart().getInventory();
		for (int i = curCartInventory.size()-1 ; i >= 0; i--) {
			InventoryItem tempInventoryItem = curCartInventory.get(i);
			if (tempInventoryItem.isSelected()) {
				curCartInventory.remove(i);
			}
		}
		this.getCart().recalculateIventory();
		return EjdConstants.SHOP_CART + "?faces-redirect=true";
	}
	public String recalCulateIventory() {
		this.getCart().recalculateIventory();
		return null;
	}
	/*public String gotoGenerateOrder() {
		String comeFrom = (String) SpringFacesUtil.getRequestParameter("comeFrom");
		if (null != comeFrom && !("".equals(comeFrom))) {
			SpringFacesUtil.setRequestMapValue("comeFrom", comeFrom);
		}
		String result = "";
		UserBean currentUser = (UserBean) SpringFacesUtil.getManagedBean(ManageBeanConstants.CURRENT_USER_BEAN_NAME);
		if (null == currentUser || null == currentUser.getUserInfo()) {
			currentUser.setComeFrom(SpringFacesUtil.getViewIdStr());
			result = "customerLogin";
		}
		return result;
	}*/
	public String selectOneCoupon(){
		List<InventoryItem> inventory = new ArrayList<InventoryItem>();
		inventory = this.getCart().getInventory();
		//is inventory is null  go to shop cart.
		if (null == inventory || inventory.isEmpty()) {
			return EjdConstants.SHOP_CART + "?faces-redirect=true";
		} 
		Coupon coupon = null;
		ICouponService couponService = (ICouponService)SpringFacesUtil.getSpringBean(SpringBeanConstants.COUPON_SERVICE_BEAN_NAME);
		couponService.setEntityClass(Coupon.class);
		couponService.setPKClass(Long.class);
		coupon = (Coupon) couponService.findUniqueBy("couponAccount",this.getCouponAccount());
		if (null == coupon) {
			this.setCouponChecked(false);
			this.setCouponScore(null);
			String couponNotExistN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.not.exist.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.setCouponErrorMessage(couponNotExistN18);
			this.getOrder().setCouponScore(0.0);
			this.getOrder().setCouponAccount("");
			return null;
		} else {
			if (null == coupon.getStatus() || "".equals(coupon.getStatus())) {
				this.setCouponChecked(false);
				this.setCouponScore(0.0);
				String couponUncertaintyN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.status.uncertainty.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.setCouponErrorMessage(couponUncertaintyN18);
				this.getOrder().setCouponScore(0.0);
				this.getOrder().setCouponAccount("");
				return null;
			}
			if (EjdConstants.COUPON_STATUS_USED.equals(coupon.getStatus())) {
				this.setCouponChecked(false);
				this.setCouponScore(0.0);
				String couponUsedN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.status.used.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.setCouponErrorMessage(couponUsedN18);
				this.getOrder().setCouponScore(0.0);
				this.getOrder().setCouponAccount("");
				return null;
			}
			if (EjdConstants.COUPON_STATUS_DISCARDED.equals(coupon.getStatus())) {
				this.setCouponChecked(false);
				this.setCouponScore(0.0);
				String couponDiscardedN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.status.discarded.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.setCouponErrorMessage(couponDiscardedN18);
				this.getOrder().setCouponScore(0.0);
				this.getOrder().setCouponAccount("");
				return null;
			}
			if (coupon.getAvailableDate().before(DateTimeUtil.getCurrentTimestamp()) || EjdConstants.COUPON_STATUS_OVERDUE.equals(coupon.getStatus())) {
				this.setCouponChecked(false);
				this.setCouponScore(0.0);
				String couponOverdueN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.status.overdue.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.setCouponErrorMessage(couponOverdueN18);
				this.getOrder().setCouponScore(0.0);
				this.getOrder().setCouponAccount("");
				return null;
			}
			if (!(EjdConstants.COUPON_STATUS_ACTIVE.equals(coupon.getStatus()))) {
				this.setCouponChecked(false);
				this.setCouponScore(0.0);
				String couponNotActiveN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.status.not.active.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.setCouponErrorMessage(couponNotActiveN18);
				this.getOrder().setCouponScore(0.0);
				this.getOrder().setCouponAccount("");
				return null;
			} else {
				 if (null != coupon.getCustomerId() && !("".equals(coupon.getCustomerId()))) {
					 if (!(LoginController.loggedIn())) {
							return EjdConstants.GO_TO_LOGIN + "?faces-redirect=true";
						}
					 LoginCustomerPageBean loginCustomerPage = (LoginCustomerPageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.LOGIN_CUSTOMER_PAGE_BEAN_NAME);
					 if (loginCustomerPage.getCustomerInfo().getCustomerId().equals(coupon.getCustomerId())) {
						 this.setCouponChecked(true);
						 this.setCouponErrorMessage("");
						 this.setCouponScore(coupon.getCouponScore());
						 this.getOrder().setCouponScore(this.getCouponScore());
						 this.getOrder().setCouponAccount(this.getCouponAccount());
						 return null;
					 } else {
						 this.setCouponChecked(false);
						 this.setCouponScore(0.0);
						 String couponOwnedBySomeBodyN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"coupon.owned.somebody.message", FacesMessage.SEVERITY_ERROR).getDetail();
						 this.setCouponErrorMessage(couponOwnedBySomeBodyN18);
						 this.getOrder().setCouponScore(0.0);
							this.getOrder().setCouponAccount("");
						 return null;
					 }
					 
				 } else {
					this.setCouponChecked(true);
					this.setCouponErrorMessage("");
					this.setCouponScore(coupon.getCouponScore());
					this.getOrder().setCouponScore(this.getCouponScore());
					this.getOrder().setCouponAccount(this.getCouponAccount());
					return null;
				}
			}
		}
	}
	
	public String useIntegrationLink() {
		if (!(LoginController.loggedIn())) {
			return EjdConstants.GO_TO_LOGIN + "?faces-redirect=true";
		}
		List<InventoryItem> inventory = new ArrayList<InventoryItem>();
		inventory = this.getCart().getInventory();
		//is inventory is null  go to shop cart.
		if (null == inventory || inventory.isEmpty()) {
			return EjdConstants.SHOP_CART + "?faces-redirect=true";
		} 
		this.setIntegrationChecked(true);
		Double integrationScore = 0.0D;
		LoginCustomerPageBean loginCustomerPage = (LoginCustomerPageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.LOGIN_CUSTOMER_PAGE_BEAN_NAME);
		if (null == loginCustomerPage.getCustomerInfo().getIntegration()) {
			loginCustomerPage.getCustomerInfo().setIntegration(0.0D);
		}
		if (this.getIntegrationScore() > loginCustomerPage.getCustomerInfo().getIntegration()) {
			integrationScore = loginCustomerPage.getCustomerInfo().getIntegration();
		} else {
			integrationScore = this.getIntegrationScore();
		}
		this.getOrder().setIntegrationScore(integrationScore);
		this.setIntegrationScore(integrationScore);
		return null;
	}
	
	public String notUseIntegrationLink() {
		this.setIntegrationChecked(false);
		this.setIntegrationScore(0D);
		this.getOrder().setIntegrationScore(0.0D);
		return null;
	}
	public void updateIntegration(ValueChangeEvent evt) {
		Double newData = (Double)(evt.getNewValue());
		this.setIntegrationScore(newData);
		this.setIntegrationChecked(false);
	}
	public void changePeriodReceiveTime(ValueChangeEvent evt) {
		String newPeriod = (String)evt.getNewValue();
		this.getOrder().setConvenientReceive(newPeriod);
	}
	public void selectDefaultAddress(ValueChangeEvent evt){
		this.getUpdateAddressErrorMessages().clear();
		boolean selectDefaultAddress = (Boolean)(evt.getNewValue());
		if (!selectDefaultAddress) {
			this.getOrderEdit().setConsigneeName("");
			this.getOrderEdit().setConsigneeMobile("");
			this.getOrderEdit().setConsigneePhone("");
			this.getOrderEdit().setConsigneeFax("");
			this.getOrderEdit().setConsigneeZip("");
			this.getOrderEdit().setConsigneeProvince("");
			this.getOrderEdit().setConsigneeCity("");
			this.getOrderEdit().setConsigneeCounty("");
			this.getOrderEdit().setConsigneeAddress("");
			this.getOrderEdit().setConsigneeId(EjdConstants.BLANK_VALUE_SELECT_ITEM);
			
		}
		if (selectDefaultAddress) {//select default address from db.
			LoginCustomerPageBean loginCustomerPage = (LoginCustomerPageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.LOGIN_CUSTOMER_PAGE_BEAN_NAME);
			IConsigneeService<Consignee,Long> consigneeService = (IConsigneeService<Consignee,Long>) SpringFacesUtil.getSpringBean(SpringBeanConstants.CONSIGNEE_SERVICE_BEAN_NAME);
			consigneeService.setEntityClass(Consignee.class);
			consigneeService.setPKClass(Long.class);
			List<Consignee> consignees = consigneeService.findBy("customerId", loginCustomerPage.getCustomerInfo().getCustomerId());
			SelectItem[] tempAddressItems;
			if (null != consignees ) {
				tempAddressItems = new SelectItem[consignees.size()+1];
			} else {
				tempAddressItems = new SelectItem[1];
			}
			String firstDefaultAddressN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"select.one.address.message", FacesMessage.SEVERITY_ERROR).getDetail();
			tempAddressItems[0]= new SelectItem(EjdConstants.BLANK_VALUE_SELECT_ITEM,firstDefaultAddressN18);
			if (null != consignees) {
				int i = 1;
				for (Consignee consignee:consignees) {
					tempAddressItems[i] = new SelectItem(consignee.getId().toString(),consignee.getShortName());
					i++;
				}
			}
			
			this.setAddressItems(tempAddressItems);
		}
	}
	public void changeAddress(ValueChangeEvent evt){
		this.getUpdateAddressErrorMessages().clear();
		String shortAddressName = (String)(evt.getNewValue());
		if (null != shortAddressName && !("".equals(shortAddressName))) {
			IConsigneeService<Consignee,Long> consigneeService = (IConsigneeService<Consignee,Long>) SpringFacesUtil.getSpringBean(SpringBeanConstants.CONSIGNEE_SERVICE_BEAN_NAME);
			consigneeService.setEntityClass(Consignee.class);
			consigneeService.setPKClass(Long.class);
			Consignee consignee = consigneeService.findById(new Long(shortAddressName));
			BeanCopier copyHere = BeanCopier.create(Consignee.class,OrderVo.class,false);
			copyHere.copy(consignee, this.getOrderEdit(), null);
		}
		SelectItem[] provinceItems = null;
		SelectItem[] cityItems = null;
		SelectItem[] countyItems = null;
		this.setProvinceItems(RegionUtil.getProvinceItems());
		this.setCityItems(RegionUtil.getCityItems(this.getOrderEdit().getConsigneeProvince()));
		this.setCountyItems(RegionUtil.getCountyItems(this.getOrderEdit().getConsigneeCity()));
	}
	public void changeProvince(ValueChangeEvent evt) {
		String newProvince = (String) evt.getNewValue();
		this.setCityItems(RegionUtil.getCityItems(newProvince));
		this.getOrderEdit().setConsigneeCity(EjdConstants.BLANK_VALUE_SELECT_ITEM);//set empty value
		this.setCountyItems(RegionUtil.getCountyItems(this.getOrderEdit().getConsigneeCity()));
		this.getOrderEdit().setConsigneeCounty(EjdConstants.BLANK_VALUE_SELECT_ITEM);
	}
	public void changeCity(ValueChangeEvent evt) {
		String newCity = (String) evt.getNewValue();
		this.setCountyItems(RegionUtil.getCountyItems(newCity));
		this.getOrderEdit().setConsigneeCounty(EjdConstants.BLANK_VALUE_SELECT_ITEM);
	}
	public String preUpdateAddress() {
		this.getUpdateAddressErrorMessages().clear();
		this.setActionSetAddress(EjdConstants.ACTION_EDIT_TYPE);
		this.getOrderEdit().setConsigneeName(this.getOrder().getConsigneeName());
		this.getOrderEdit().setConsigneeMobile(this.getOrder().getConsigneeMobile());
		this.getOrderEdit().setConsigneePhone(this.getOrder().getConsigneePhone());
		this.getOrderEdit().setConsigneeFax(this.getOrder().getConsigneeFax());
		this.getOrderEdit().setConsigneeZip(this.getOrder().getConsigneeZip());
		this.getOrderEdit().setConsigneeProvince(this.getOrder().getConsigneeProvince());
		this.getOrderEdit().setConsigneeCity(this.getOrder().getConsigneeCity());
		this.getOrderEdit().setConsigneeCounty(this.getOrder().getConsigneeCounty());
		this.getOrderEdit().setConsigneeAddress(this.getOrder().getConsigneeAddress());
		this.getOrderEdit().setConsigneeId(this.getOrder().getConsigneeId());
		this.setSuccessSetAddress(false);
		this.setProvinceItems(RegionUtil.getProvinceItems());
		this.setCityItems(RegionUtil.getCityItems(this.getOrderEdit().getConsigneeProvince()));
		this.setCountyItems(RegionUtil.getCountyItems(this.getOrderEdit().getConsigneeCity()));
		return null;
	}
	public String preUpdateInvoice() {
		this.getUpdateInvoiceErrorMessages().clear();
		this.setActionSetInvoice(EjdConstants.ACTION_EDIT_TYPE);
		if (EjdConstants.INVOICE_TYPE_PLAIN.equals(this.getOrder().getInvoiceType())) {
			this.getOrderEdit().setInvoiceType(this.getOrder().getInvoiceType());
			this.getOrderEdit().setInvoiceTypeDisplay(this.getOrder().getInvoiceTypeDisplay());
			this.getOrderEdit().setInvoiceTitle(this.getOrder().getInvoiceTitle());
		} else if (EjdConstants.INVOICE_TYPE_VAT.equals(this.getOrder().getInvoiceType())) {
			this.getOrderEdit().setInvoiceType(this.getOrder().getInvoiceType());
			this.getOrderEdit().setInvoiceTypeDisplay(this.getOrder().getInvoiceTypeDisplay());
			this.getOrderEdit().setInvoiceCompanyName(this.getOrder().getInvoiceCompanyName());
			this.getOrderEdit().setInvoiceCompanyAddress(this.getOrder().getInvoiceCompanyAddress());
			this.getOrderEdit().setInvoiceCompanyPhone(this.getOrder().getInvoiceCompanyPhone());
			this.getOrderEdit().setTaxAccount(this.getOrder().getTaxAccount());
			this.getOrderEdit().setBankName(this.getOrder().getBankName());
			this.getOrderEdit().setAccountNumber(this.getOrder().getAccountNumber());
			this.getOrderEdit().setInvoicePostAddress(this.getOrder().getInvoicePostAddress());
		}
		return null;
	}
	public String submitAddress(){
		this.getUpdateAddressErrorMessages().clear();
		ValidatorUtil.nameValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeName());
		ValidatorUtil.phoneMobileValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeMobile());
		String consigneePhoneN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"phone.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.phoneValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneePhone(),consigneePhoneN18);
		ValidatorUtil.PhoneExtValidator(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeFax());
		String addressNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"address.empty.error.parram", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeAddress(), addressNameN18);
		String provinceNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"province.empty.error.parram", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeProvince(), provinceNameN18);
		String cityNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"city.empty.error.parram", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeCity(),cityNameN18);
		String countyNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"county.empty.error.parram", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeCounty(), countyNameN18);
		ValidatorUtil.addressValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeAddress());
		if (null != this.getUpdateAddressErrorMessages() && this.getUpdateAddressErrorMessages().size() > 0) {
			return null;
		}
		this.getOrder().setConsigneeName(this.getOrderEdit().getConsigneeName());
		this.getOrder().setConsigneeMobile(this.getOrderEdit().getConsigneeMobile());
		this.getOrder().setConsigneePhone(this.getOrderEdit().getConsigneePhone());
		this.getOrder().setConsigneeFax(this.getOrderEdit().getConsigneeFax());
		this.getOrder().setConsigneeZip(this.getOrderEdit().getConsigneeZip());
		this.getOrder().setConsigneeProvince(this.getOrderEdit().getConsigneeProvince());
		this.getOrder().setConsigneeCity(this.getOrderEdit().getConsigneeCity());
		this.getOrder().setConsigneeCounty(this.getOrderEdit().getConsigneeCounty());
		this.getOrder().setConsigneeAddress(this.getOrderEdit().getConsigneeAddress());
		this.getOrder().setConsigneeId(this.getOrderEdit().getConsigneeId());
		this.setSuccessSetAddress(true);
		this.setActionSetAddress(EjdConstants.ACTION_VIEW_TYPE);
		return null;
	}
	public String cancelSetAddress(){
		this.setActionSetAddress(EjdConstants.ACTION_VIEW_TYPE);
		return EjdConstants.CREATE_ORDER + "?faces-redirect=true";
	}
	public void cancelSetInvoice(ActionEvent e){
		this.setActionSetInvoice(EjdConstants.ACTION_VIEW_TYPE);
	}
	public void changeInvoiceType(ValueChangeEvent e){
		String newInvoiceType = (String)e.getNewValue();
		if (null != this.getUpdateInvoiceErrorMessages() && !(this.getUpdateInvoiceErrorMessages().isEmpty())) {
			this.getUpdateInvoiceErrorMessages().clear();
		}
		ExistInvoiceTypeBean existInvoiceType = (ExistInvoiceTypeBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.EXIST_INVOICE_TYPE_BEAN);
		SelectItem[] invoiceTypeItems = existInvoiceType.getInvoiceTypeItems();
		String newInvoiceTypeDisplay = "";
		for (SelectItem item:invoiceTypeItems) {
			String descOfInvoiceType = item.getLabel();
			String valueOfInvoiceType = (String)item.getValue();
			if (newInvoiceType.equals(valueOfInvoiceType)) {
				newInvoiceTypeDisplay = descOfInvoiceType;
				break;
			}
		}
		this.getOrderEdit().setInvoiceTypeDisplay(newInvoiceTypeDisplay);
	}
	public String selectDediveryId(){
		String deliveryId = (String)SpringFacesUtil.getRequestParameter("deliveryId");
		String deliveryName = (String)SpringFacesUtil.getRequestParameter("deliveryName");
		Double deliveryExpense = new Double(null == SpringFacesUtil.getRequestParameter("deliveryExpense")?"0.0":SpringFacesUtil.getRequestParameter("deliveryExpense").toString());
		String deliveryDescription = (String)SpringFacesUtil.getRequestParameter("deliveryDescription");
		this.getOrder().setDeliveryId(deliveryId);
		this.getOrder().setDeliveryName(deliveryName);
		this.getOrder().setDeliveryExpense(deliveryExpense);
		this.getOrder().setDeliveryDescription(deliveryDescription);
		return null;
	}
	public String selectPaymentType(){
		String paymentType = (String)SpringFacesUtil.getRequestParameter("paymentType");
		String paymentTypeDisplay = (String)SpringFacesUtil.getRequestParameter("paymentTypeDisplay");
		this.getOrder().setPaymentType(paymentType);
		this.getOrder().setPaymentTypeDisplay(paymentTypeDisplay);
		this.setPayments(PaymentUtil.getPaymentsByPaymentTypeId(paymentType));
		return null;
	}
	public String selectPaymentId(){
		String paymentId = (String)SpringFacesUtil.getRequestParameter("paymentId");
		String paymentName = (String)SpringFacesUtil.getRequestParameter("paymentName");
		Double paymentExpense = (Double)SpringFacesUtil.getRequestParameter("paymentExpense;");
		String paymentDescription = (String)SpringFacesUtil.getRequestParameter("paymentDescription");
		String paymentTypeId = (String)SpringFacesUtil.getRequestParameter("paymentTypeId");
		this.getOrder().setPaymentId(paymentId);
		this.getOrder().setPaymentName(paymentName);
		this.getOrder().setPaymentExpense(paymentExpense);
		this.getOrder().setPaymentDescription(paymentDescription);
		this.getOrder().setPaymentTypeId(paymentTypeId);
		return null;
	}
	public String submitInvoice(){
		this.getUpdateInvoiceErrorMessages().clear();
		/*ValidatorUtil.nameValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeName());
		ValidatorUtil.phoneMobileValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeMobile());
		ValidatorUtil.phoneValidate(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneePhone());
		ValidatorUtil.PhoneExtValidator(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeFax());
		String addressNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"address.empty.error.parram", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidator(this.getUpdateAddressErrorMessages(), this.getOrderEdit().getConsigneeAddress(), addressNameN18);
		*/
		if (EjdConstants.INVOICE_TYPE_PLAIN.equals(this.getOrderEdit().getInvoiceType())) {
			String invoiceTitleN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.title.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceTitle(), invoiceTitleN18);
			
		}
		if (EjdConstants.INVOICE_TYPE_VAT.equals(this.getOrderEdit().getInvoiceType())) {
			String invoiceCompanyNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.company.name.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceCompanyName(), invoiceCompanyNameN18);
			String invoiceCompanyAddressN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.company.address.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceCompanyAddress(), invoiceCompanyAddressN18);
			ValidatorUtil.addressValidate(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceCompanyAddress());
			String invoiceCompanyPhoneN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.company.phone.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceCompanyPhone(), invoiceCompanyPhoneN18);
			ValidatorUtil.phoneValidate(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoiceCompanyPhone(),invoiceCompanyPhoneN18);
			String taxAccountN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.tax.account.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getTaxAccount(), taxAccountN18);
			String bankNameN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.bank.name.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getBankName(), bankNameN18);
			String accountNumberN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.account.number.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getAccountNumber(), accountNumberN18);
			String invoicePostAddressN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.post.address.display", FacesMessage.SEVERITY_ERROR).getDetail();
			ValidatorUtil.EmptyValidatorForInput(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoicePostAddress(), invoicePostAddressN18);
			ValidatorUtil.addressValidate(this.getUpdateInvoiceErrorMessages(), this.getOrderEdit().getInvoicePostAddress());
		}
		if (null != this.getUpdateInvoiceErrorMessages() && this.getUpdateInvoiceErrorMessages().size() > 0) {
			return null;
		}
		this.setActionSetInvoice(EjdConstants.ACTION_VIEW_TYPE);
		if (EjdConstants.INVOICE_TYPE_PLAIN.equals(this.getOrderEdit().getInvoiceType())) {
			this.getOrder().setInvoiceType(this.getOrderEdit().getInvoiceType());
			this.getOrder().setInvoiceTypeDisplay(this.getOrderEdit().getInvoiceTypeDisplay());
			this.getOrder().setInvoiceTitle(this.getOrderEdit().getInvoiceTitle());
		} else if (EjdConstants.INVOICE_TYPE_VAT.equals(this.getOrderEdit().getInvoiceType())) {
			this.getOrder().setInvoiceType(this.getOrderEdit().getInvoiceType());
			this.getOrder().setInvoiceTypeDisplay(this.getOrderEdit().getInvoiceTypeDisplay());
			this.getOrder().setInvoiceCompanyName(this.getOrderEdit().getInvoiceCompanyName());
			this.getOrder().setInvoiceCompanyAddress(this.getOrderEdit().getInvoiceCompanyAddress());
			this.getOrder().setInvoiceCompanyPhone(this.getOrderEdit().getInvoiceCompanyPhone());
			this.getOrder().setTaxAccount(this.getOrderEdit().getTaxAccount());
			this.getOrder().setBankName(this.getOrderEdit().getBankName());
			this.getOrder().setAccountNumber(this.getOrderEdit().getAccountNumber());
			this.getOrder().setInvoicePostAddress(this.getOrderEdit().getInvoicePostAddress());
		}
		this.setSuccessSetInvoice(true);
		return null;
	}
	public void changeCouponAccount(ValueChangeEvent e){
		this.setCouponErrorMessage("");
		this.setCouponChecked(false);
		this.setCouponScore(0.0);
	}
	public String useOtherCoupon() {
		this.setCouponErrorMessage("");
		this.setCouponChecked(false);
		return null;
	}
	public String goToGenerateOrder() {
		clearCouponAndIntegrationData();
		return EjdConstants.CREATE_ORDER + "?faces-redirect=true";
	}
	public String generateOrder() throws Exception{
		this.getOrderErrorMessage().clear();
		String result = null;
		if (!(LoginController.loggedIn())) {
			return EjdConstants.GO_TO_LOGIN + "?faces-redirect=true";
		}
		if (!this.isSuccessSetAddress()) {
			String deliveryN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"consignee.info.need.completed.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.getOrderErrorMessage().add(deliveryN18);
		}
		if (null == this.getOrder().getDeliveryId() || "".equals(this.getOrder().getDeliveryId())) {
			
			String sendN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"send.info.need.completed.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.getOrderErrorMessage().add(sendN18);
		}
		if (null == this.getOrder().getConvenientReceive() || "".equals(this.getOrder().getConvenientReceive())) {
			
			String convenientReceiveN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"convenient.receive.need.completed.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.getOrderErrorMessage().add(convenientReceiveN18);
		}
		if (null == this.getOrder().getPaymentTypeId() || "".equals(this.getOrder().getPaymentTypeId())) {
			String paymentN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"payment.info.need.completed.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.getOrderErrorMessage().add(paymentN18);
		}
		if (null == this.getOrder().getInvoiceType() || "".equals(this.getOrder().getInvoiceType())) {
			String invoiceN18 = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME,"invoice.info.need.completed.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.getOrderErrorMessage().add(invoiceN18);
		}
		if (null != this.getOrderErrorMessage() && !(this.getOrderErrorMessage().isEmpty())) {
			return null;
		}
		LoginCustomerPageBean loginCustomerPage = (LoginCustomerPageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.LOGIN_CUSTOMER_PAGE_BEAN_NAME);
		Order order = new Order();
		String ncode = EjdConstants.ORDER_PREFIX+DateTimeUtil.getCurrentYearMonth();
		INCounterService ncounterService = (INCounterService)SpringFacesUtil.getSpringBean(SpringBeanConstants.NCOUNTER_SERVICE_BEAN_NAME);
		ncounterService.setEntityClass(NCounter.class);
		ncounterService.setPKClass(Long.class);
		NCounter ncounter =(NCounter)ncounterService.findUniqueBy("code", ncode);
		Integer last= ncounter.getCounterLast();
		Integer next = ncounter.getCounterNext();
		String orderId = NCounterUtil.getNo(ncounter);
		//update ncounter
		NCounter newNCounter = new NCounter();
		BeanCopier copyNCounter = BeanCopier.create(NCounter.class, NCounter.class, false);
		copyNCounter.copy(ncounter, newNCounter, null);
		newNCounter.setCounterLast(last + 1);
		newNCounter.setCounterNext(next + 1);
		ncounterService.saveOrUpdate(newNCounter);
		//end
		order.setId(null);
		order.setOrderId(orderId);
		order.setStatus(EjdConstants.ORDER_STATUS_WAITING_FOR_BEING_REVIEWED);
		order.setConsigneeId(this.getOrder().getConsigneeId());
		order.setConsigneeName(this.getOrder().getConsigneeName());
		order.setConsigneeMobile(this.getOrder().getConsigneeMobile());
		order.setConsigneePhone(this.getOrder().getConsigneePhone());
		order.setConsigneeFax(this.getOrder().getConsigneeFax());
		order.setConsigneeZip(this.getOrder().getConsigneeZip());
		order.setConsigneeProvince(this.getOrder().getConsigneeProvince());
		order.setConsigneeCity(this.getOrder().getConsigneeCity());
		order.setConsigneeCounty(this.getOrder().getConsigneeCounty());
		order.setConsigneeAddress(this.getOrder().getConsigneeAddress());
		order.setDeliveryId(this.getOrder().getDeliveryId());
		order.setDeliveryName(this.getOrder().getDeliveryName());
		order.setDeliveryExpense(this.getOrder().getDeliveryExpense());
		order.setDeliveryDescription(this.getOrder().getDeliveryDescription());
		order.setPaymentType(this.getOrder().getPaymentType());
		order.setPaymentTypeDisplay(this.getOrder().getPaymentTypeDisplay());
		order.setPaymentId(this.getOrder().getPaymentId());
		order.setPaymentName(this.getOrder().getPaymentName());
		order.setPaymentExpense(this.getOrder().getPaymentExpense());
		order.setPaymentDescription(this.getOrder().getPaymentDescription());
		order.setPaymentTypeId(this.getOrder().getPaymentTypeId());
		order.setInvoiceType(this.getOrder().getInvoiceType());
		order.setInvoiceTypeDisplay(this.getOrder().getInvoiceTypeDisplay());
		order.setInvoiceTitle(this.getOrder().getInvoiceTitle());
		order.setInvoiceCompanyName(this.getOrder().getInvoiceCompanyName());
		order.setInvoiceCompanyAddress(this.getOrder().getInvoiceCompanyAddress());
		order.setInvoiceCompanyPhone(this.getOrder().getInvoiceCompanyPhone());
		order.setTaxAccount(this.getOrder().getTaxAccount());
		order.setBankName(this.getOrder().getBankName());
		order.setAccountNumber(this.getOrder().getAccountNumber());
		order.setInvoicePostAddress(this.getOrder().getInvoicePostAddress());
		order.setConvenientReceive(this.getOrder().getConvenientReceive());
		order.setRemark(this.getOrder().getRemark());
		order.setOrderGenerateTime(DateTimeUtil.getCurrentTimestamp());
		order.setCouponAccount(this.getOrder().getCouponAccount());
		order.setCouponScore(this.getOrder().getCouponScore());
		order.setIntegrationScore(this.getOrder().getIntegrationScore());
		order.setTotallPrice(this.getCart().getInventoryPriceTotal());
		Double needPay = 0.0D;
		needPay = calculateNeedPay(order);
		order.setNeedPayment(needPay);
		order.setCustomer(loginCustomerPage.getCustomerInfo());
		Set<OrderDetail> orderDetails = new HashSet<OrderDetail>();
		List<InventoryItem> inventory = new ArrayList<InventoryItem>();
		inventory = this.getCart().getInventory();
		//is inventory is null  go to shop cart.
		if (null == inventory || inventory.isEmpty()) {
			return EjdConstants.SHOP_CART + "?faces-redirect=true";
		} else {
			for (int i = 0; i < inventory.size(); i++) {
				InventoryItem inventoryItem = inventory.get(i);
				OrderDetail orderDetail = new OrderDetail();
				BeanCopier copyOrderDetail = BeanCopier.create(InventoryItem.class, OrderDetail.class, false);
				copyOrderDetail.copy(inventoryItem, orderDetail, null);
				orderDetail.setId(null);
				orderDetail.setOrder(order);
				orderDetails.add(orderDetail);
			}
		}
		order.setOrderDetails(orderDetails);
		IOrderService orderService = (IOrderService)SpringFacesUtil.getSpringBean(SpringBeanConstants.ORDER_SERVICE_BEAN_NAME);
		orderService.setEntityClass(Order.class);
		orderService.setPKClass(Long.class);
		orderService.save(order);
		//end
		//clear goods
		this.getCart().getInventory().clear();
		this.getCart().recalculateIventory();
		//end
		//update Coupon if used
		if (null != this.getOrder().getCouponAccount() && !("".equals(this.getOrder().getCouponAccount()))) {
			ICouponService couponService = (ICouponService)SpringFacesUtil.getSpringBean(SpringBeanConstants.COUPON_SERVICE_BEAN_NAME);
			couponService.setEntityClass(Coupon.class);
			couponService.setPKClass(Long.class);
			Coupon coupon = (Coupon) couponService.findUniqueBy("couponAccount",this.getOrder().getCouponAccount());
			coupon.setStatus(EjdConstants.COUPON_STATUS_USED);
			coupon.setCustomerId(loginCustomerPage.getCustomerInfo().getCustomerId());
			couponService.saveOrUpdate(coupon);
			this.setCouponChecked(false);
			this.getOrder().setCouponAccount("");
			this.getOrder().setCouponScore(0.0);
			this.setCouponAccount("");
			this.setCouponScore(0.0);
		}
		//end
		// if setIntegrationScore is not zero ,then
		ICustomerService customerService = (ICustomerService)SpringFacesUtil.getSpringBean(SpringBeanConstants.CUSTOMER_SERVICE_BEAN_NAME);
		customerService.setEntityClass(Customer.class);
		customerService.setPKClass(Long.class);
		if (null != order.getIntegrationScore() && order.getIntegrationScore() > 0D) {
		Customer customer = (Customer) customerService.get(loginCustomerPage.getCustomerInfo().getId());
		Double integration = customer.getIntegration();
		customer.setIntegration(integration - order.getIntegrationScore());
		customerService.saveOrUpdate(customer);
		//reread customer
		loginCustomerPage.setCustomerInfo(customer);
		//
		}
		//end
		
		//clear integration and coupon
		clearCouponAndIntegrationData();
		//end
		
		DESPlusUtil desUtil = new DESPlusUtil();
		return EjdConstants.ORDER_PAY + "?faces-redirect=true&orderId=" + desUtil.encrypt(orderId);
	}
	public String goDetailPage(){
		String result = "";
		String primaryCategoryCode = (String) SpringFacesUtil.getRequestParameter("primaryCategoryCode");
		String code =(String) SpringFacesUtil.getRequestParameter("code");
		String productId =(String) SpringFacesUtil.getRequestParameter("productId");
		String specialField1 = (String) SpringFacesUtil.getRequestParameter("specialField1");
		String specialField2 = (String) SpringFacesUtil.getRequestParameter("specialField2");
		if (PageExistUtil.checkPageExist(code+".xhtml", "/layout/goods/" + primaryCategoryCode) && PageExistUtil.checkPageExist(code+"Detail.xhtml", "/layout/goods/" + primaryCategoryCode + "/sub") ) {
			result =  "/layout/goods/" + primaryCategoryCode + "/" + code + "?faces-redirect=true&primaryCategoryCode=" + DESPlusUtil.encrypt(primaryCategoryCode) + "&code=" + DESPlusUtil.encrypt(code) + "&productId=" + DESPlusUtil.encrypt(productId);
			if (null != specialField1 && !("".equals(specialField1))) {
				result = result + "&specialField1=" + DESPlusUtil.encrypt(specialField1);
			}
			if (null != specialField2 && !("".equals(specialField2))) {
				result = result + "&specialField2=" + DESPlusUtil.encrypt(specialField2);
			}
			return result;
		} else {
			return "/WEB-INF/" + EjdConstants.NO_PRODUCT_DETAIL_PAGE;
		}
	}
	// following function used for update order start
	public String searchOrderForUpdate() {
		String orderId =(String) SpringFacesUtil.getRequestParameter("orderId");
		if (null == orderId || "".equals(orderId)) {
			return null;
		}
		/*IOrderService orderService = (IOrderService)SpringFacesUtil.getSpringBean(SpringBeanConstants.ORDER_SERVICE_BEAN_NAME);
		orderService.setEntityClass(Order.class);
		orderService.setPKClass(Long.class);
		Order order = (Order) orderService.findUniqueBy("orderId", orderId);
		OrderVo orderVo = new OrderVo();
		BeanCopier customerCopy = BeanCopier.create(Customer.class,CustomerVo.class,false);
		customerCopy.copy(order.getCustomer(), orderVo.getCustomer(), null);
		BeanCopier orderDetailCopy = BeanCopier.create(OrderDetail.class,OrderDetailVo.class,false);
		orderDetailCopy.copy(order.getOrderDetails(), orderVo.getOrderDetails(), null);
		BeanCopier copyOrder = BeanCopier.create(Order.class, OrderVo.class, true);
		copyOrder.copy(order, orderVo, null);*/
		System.out.println("====");
		return null;
	}
	
	// following function used for update order end
	
	private void clearCouponAndIntegrationData(){
		this.setCouponAccount("");
		this.setCouponErrorMessage("");
		if (null != this.getOrder().getCouponAccount() && !("".equals(this.getOrder().getCouponAccount()))) {
			this.getOrder().setCouponAccount(null);
		}
		this.setCouponScore(0.0D);
		if (null != this.getOrder().getCouponScore() && this.getOrder().getCouponScore() > 0.0D) {
			this.getOrder().setCouponScore(0.0D);
		}
		this.setCouponChecked(false);
		this.setIntegrationScore(0.0D);
		if (null != this.getOrder().getIntegrationScore() && this.getOrder().getIntegrationScore() > 0.0D) {
			this.getOrder().setIntegrationScore(0.0D);
		}
		this.setIntegrationChecked(false);
	}
	private Double calculateNeedPay(Order order){
		Double result = 0.0D;
		result = order.getTotallPrice();
		if (null != order.getDeliveryExpense()) {
			result = result + order.getDeliveryExpense();
		}
		if (null != order.getCouponScore()) {
			result = result - order.getCouponScore();
		}
		if (null != order.getIntegrationScore()) {
			result = result - order.getIntegrationScore()/10;
		}
		return result;
	}
}
